// 基础响应接口
export interface BaseResponse<T = any> {
    code: string;
    message: string;
    data?: T;
}

// 分页响应接口
export interface PageResponse<T> {
    total: number;
    records: T[];
}

// 分页请求参数接口
export interface PageParams {
    pageIndex?: number;
    pageSize?: number;
    [key: string]: any;
}

// HTTP错误类
export class HttpError extends Error {
    constructor(public status: number, message: string) {
        super(message);
        this.name = 'HttpError';
    }
}

// API错误类
export class ApiError extends Error {
    constructor(public code: string, message: string) {
        super(message);
        this.name = 'ApiError';
    }
}

// 获取认证令牌
export const getToken = (): string => {
    const storedToken = localStorage.getItem('auth_token');
    if (!storedToken) throw new Error('用户未登录');
    return storedToken;
};

// 构建查询字符串
export const buildQueryString = (params: PageParams): string => {
    const queryParams = new URLSearchParams();
    queryParams.append('pageIndex', String(params.pageIndex || 1));
    queryParams.append('pageSize', String(params.pageSize || 10));

    Object.entries(params).forEach(([key, value]) => {
        if (key !== 'pageIndex' && key !== 'pageSize' && value) {
            queryParams.append(key, String(value));
        }
    });

    return `?${queryParams.toString()}`;
};

// 处理HTTP响应
async function handleResponse<T>(response: Response): Promise<T> {
    const data: BaseResponse<T> = await response.json();
    if (!response.ok) {
        if (data.code.length == 6 && data.code.startsWith('10')) {
            throw new HttpError(401, data.message);
        } else {
            throw new HttpError(response.status, data.message);
        }
    }
    if (data.code !== '0') {
        throw new ApiError(data.code, data.message);
    }

    return data.data as T;
}

// 错误处理函数
function handleError(error: unknown): never {
    if (error instanceof HttpError) {
        if (error.status === 401) {
            localStorage.removeItem('auth_token');
            window.location.href = '/login';
        }
        throw error.message;
    } else if (error instanceof ApiError) {
        throw error.message;
    } else {
        throw '未知错误，请稍后重试';
    }
}



// HTTP请求封装
export async function request<T>(
    url: string,
    options: RequestInit = {},
    noAuth?: boolean // 免认证
): Promise<T> {
    try {
        let authHeaders = {};
        if (!noAuth) {
            const token = getToken();
            authHeaders = {
                'Authorization': `Bearer ${token}`,
            };
        }

        const response = await fetch(url, {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                ...authHeaders,
                ...options.headers,
            },
        });

        return await handleResponse<T>(response);
    } catch (error) {
        return handleError(error);
    }
}

// GET请求
export const get = <T>(url: string) => request<T>(url);

// POST请求
export const post = <T>(url: string, data: any) =>
    request<T>(url, {
        method: 'POST',
        body: JSON.stringify(data),
    });

// PUT请求
export const put = <T>(url: string, data: any) =>
    request<T>(url, {
        method: 'PUT',
        body: JSON.stringify(data),
    });

// DELETE请求
export const del = <T>(url: string) =>
    request<T>(url, {
        method: 'DELETE',
    });


export const postWithoutAuth = <T>(url: string, data: any) =>
    request<T>(url, {
        method: 'POST',
        body: JSON.stringify(data),
    }, true);

export const getWithoutAuth = <T>(url: string) =>
    request<T>(url, {}, true);